
package com.yimixian.app.fragment;

import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.activity.YMXMainActivity;
import com.yimixian.app.adapter.OrdersListViewAdapter;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.WebViewActivity;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.model.Order;
import com.yimixian.app.mvp.basehttp.BaseHttpMvpFragment;
import com.yimixian.app.mvp.presenter.OrderListPresenter;
import com.yimixian.app.mvp.view.OrderListMvpView;
import com.yimixian.app.order.OrderDetailActivity;
import com.yimixian.app.ui.SlideViewPager;
import com.yimixian.app.ui.pull.PullRefreshLayout;
import com.yimixian.app.util.Strings;
import com.ymx.sdk.widget.ListViewLoadMore.AutoPullToRefreshListView;
import com.ymx.sdk.widget.PullToRefreshView.PullToRefreshBase;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import butterknife.ButterKnife;
import butterknife.InjectView;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

public class OrderMvpFragment extends BaseHttpMvpFragment implements
        AutoPullToRefreshListView.OnLoadMoreListener,
        PullToRefreshBase.OnRefreshListener2<ListView>, OrderListMvpView,
        SlideViewPager.ISlideViewPager {

    View mOrderView;
    View mGroupView;
    AutoPullToRefreshListView mOrdersListView;
    WebView mWebView;
    PullRefreshLayout refresh_layout;
    @InjectView(R.id.iv_no_login)
    ImageView mIvNoLogin;
    @InjectView(R.id.tv_login)
    TextView mTvLogin;
    @InjectView(R.id.rl_login)
    RelativeLayout mRlLogin;
    @InjectView(R.id.tv_button_txt)
    TextView mTvButtonTxt;
    ViewPager mViewPager;
    @InjectView(R.id.slide_view)
    SlideViewPager mSlideView;
    private View mNoData;
    private boolean is_commit = false;
    OrdersListViewAdapter adapter;
    public OrderListPresenter mPresenter;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.arg1 == 0) {
                is_commit = true;
            }
        }
    };

    public static String CHANG_FLAG = "";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.show_orders_activity, null);
        mNoData = view.findViewById(R.id.order_no_data);
        ButterKnife.inject(this, view);
        LayoutInflater layoutInflater = getActivity().getLayoutInflater().from(getActivity());
        mOrderView = layoutInflater.inflate(R.layout.fragment_order_list, null);
        mGroupView = layoutInflater.inflate(R.layout.fragment_order_group, null);
        refresh_layout = (PullRefreshLayout) mGroupView.findViewById(R.id.refresh_layout);
        mSlideView.bind(this);
        mSlideView.showDivider();
        initPresenter();
        initNodataView();

        refresh_layout.setRefreshStyle(PullRefreshLayout.YMX_PULL_DRAWABLE);
        refresh_layout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if(mWebView != null){
                            mWebView.reload();
                        }
                    }
                }, 800);
            }
        });

        return view;
    }

    public void changeOneData(int position, String type){
        if(adapter != null && adapter.getCount() > position){
            if("deleted".equals(type)){
                adapter.getList().remove(position);
                adapter.notifyDataSetChanged();
            }else if("canceled".equals(type)){
                Order order = adapter.getList().get(position);
                order.status = 0;
                adapter.notifyDataSetChanged();
            }
        }
    }

    public void initPresenter() {
        mPresenter = new OrderListPresenter();
        mPresenter.attachView(this);
        mPresenter.initData();
        mPresenter.loadData();
    }

    public void initPresenter(int position, String type) {
        mPresenter = new OrderListPresenter();
        mPresenter.attachView(this);
        mPresenter.initData();
        if(mPresenter.getOrders() != null && mPresenter.getOrders().size() > position){
            if("canceled".equals(type)){
                mPresenter.getOrders().get(position).status = 0;
            }else if("deleted".equals(type)){
                mPresenter.getOrders().remove(position);
            }
            adapter.notifyDataSetInvalidated();
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void initRightView() {
        mWebView = (WebView) mGroupView.findViewById(R.id.order_webview);
        mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Uri uri = Uri.parse(url);
                if (uri.getScheme() != null && uri.getScheme().equals("ymxian")) {
                    dealCustomProtocol(uri);
                } else {
                    if (url.endsWith(".apk")) {
                        Intent viewIntent = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(viewIntent);
                        return true;
                    }
                    view.loadUrl(appendTokenIfNecessary(url));
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (refresh_layout != null) {
                    refresh_layout.setRefreshing(false);
                }
            }
        });

        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setBlockNetworkImage(false);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setUserAgentString(settings.getUserAgentString() + " YMXian/"
                + DataManager.getInstance().get(CacheKeys.VERSION_NAME));
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int progress) {
                if (progress < 100) {
                } else if (progress == 100) {
                }
            }
        });
        mPresenter.loadUrl();
    }

    private String appendTokenIfNecessary(String url) {
        String token = DataManager.getInstance().get(CacheKeys.TOKEN);
        Uri uri = Uri.parse(url);
        if (TextUtils.isEmpty(uri.getHost())) {
            return url;
        }
        if (Strings.isNullOrEmpty(token) || !uri.getHost().endsWith(".1mxian.com")) {
            return url;
        }
        return url + (url.contains("?") ? "&token=" : "?token=") + token;
    }

    @Override
    public void initLeftView() {
        mViewPager = (ViewPager) mOrderView.findViewById(R.id.view_pager);
        mOrdersListView = (AutoPullToRefreshListView) mOrderView.findViewById(R.id.orders_list);
        mOrdersListView.setOnLoadMoreListener(this);
        adapter = new OrdersListViewAdapter(
                getActivity());
        adapter.setHandler(mHandler);
        adapter.setList(mPresenter.getOrders());
        mOrdersListView.setAdapter(adapter);
        mOrdersListView.setOnRefreshListener(this);
        mOrdersListView.addFrontView(true);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mOrdersListView != null) {
            mOrdersListView.onRefreshComplete();
        }
    }

    @Override
    public void onStart() {
        super.onStart();

    }

    @Override
    public void onResume() {
        super.onResume();
        is_commit = mPresenter.onResumeCheck(is_commit);
    }

    @Override
    public void onDetach() {
        hideDialog();
        super.onDetach();
    }

    public void initNodataView() {

        mIvNoLogin = (ImageView) mOrderView.findViewById(R.id.iv_no_login);
        mTvLogin = (TextView) mOrderView.findViewById(R.id.tv_login);
        mTvButtonTxt = (TextView) mOrderView.findViewById(R.id.tv_button_txt);
        mRlLogin = (RelativeLayout) mOrderView.findViewById(R.id.rl_login);
        mIvNoLogin.setImageResource(R.drawable.ic_no_order_data);
        mTvLogin.setText(getString(R.string.order_no_data_tips));
        mTvButtonTxt.setText(getString(R.string.go_home));
        mRlLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getActivity() instanceof YMXMainActivity) {
                    ((YMXMainActivity) getActivity()).setHomeTab();
                }
            }
        });

//        mIvNoLogin = (ImageView) mGroupView.findViewById(R.id.iv_no_login);
//        mTvLogin = (TextView) mGroupView.findViewById(R.id.tv_login);
//        mTvButtonTxt = (TextView) mGroupView.findViewById(R.id.tv_button_txt);
//        mRlLogin = (RelativeLayout) mGroupView.findViewById(R.id.rl_login);
//        mIvNoLogin.setImageResource(R.drawable.ic_no_order_data);
//        mTvLogin.setText(getString(R.string.order_no_data_tips));
//        mTvButtonTxt.setText(getString(R.string.go_home));
//        mRlLogin.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (getActivity() instanceof YMXMainActivity) {
//                    ((YMXMainActivity) getActivity()).setHomeTab();
//                }
//            }
//        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mPresenter.detachView();
    }

    @Override
    public void onLoadMore() {
        mPresenter.onLoadMore();
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mPresenter.onPullDownToRefresh();
            }
        }, 800);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

    }

    @Override
    public void showLoadingDataUI() {
        showLoadingDialog("载入订单...", false);
    }

    @Override
    public void hideLoadingDataUI() {
        hideDialog();
    }

    @Override
    public void showHttpSucUI() {
        adapter.setList(mPresenter.getOrders());
    }

    @Override
    public void showHttpFailUI(String failInfo) {
        super.showHttpFailUI(failInfo);
    }

    @Override
    public void onLoadMoreComplete() {
        mOrdersListView.onLoadMoreComplete();
    }

    @Override
    public void onRefreshComplete() {
        mOrdersListView.onRefreshComplete();
    }

    @Override
    public void showNoDataUI() {
        mOrderView.findViewById(R.id.order_no_data).setVisibility(View.VISIBLE);
//        mGroupView.findViewById(R.id.order_no_data).setVisibility(View.VISIBLE);
//        mNoData.setVisibility(View.VISIBLE);
        mOrdersListView.setVisibility(View.GONE);
    }

    @Override
    public void hideNoDataUI() {
        mOrderView.findViewById(R.id.order_no_data).setVisibility(View.GONE);
//        mGroupView.findViewById(R.id.order_no_data).setVisibility(View.GONE);
//        mNoData.setVisibility(View.GONE);
        mOrdersListView.setVisibility(View.VISIBLE);
    }

    @Override
    public void setListViewEnable(boolean enable) {
        mOrdersListView.setIsEnable(enable);
    }

    @Override
    public void loadURL(String url) {
        mWebView.loadUrl(url);
    }

    @Override
    public View getLeftView() {
        return mOrderView;
    }

    @Override
    public View getRightView() {
        return mGroupView;
    }

    @Override
    public String getLeftTitleName() {
        return SystemFramework.getInstance().getGlobalContext().getString(R.string.my_order);
    }

    @Override
    public String getRightTitleName() {
        return SystemFramework.getInstance().getGlobalContext().getString(R.string.my_group);
    }

    @Override
    public void onBackButtonClick() {

    }

    private void dealCustomProtocol(final Uri uri) {
        Intent intent;
        if (uri.getHost() == null) {
            if (isAdded()) {
                getActivity().finish();
            }
            return;
        }
        switch (uri.getHost()) {

            case ("push_webview"):
                String weburl = "";
                weburl = uri.getQueryParameter("url");
                try {
                    if (!TextUtils.isEmpty(weburl)) {
                        weburl = URLDecoder.decode(weburl, "utf-8");
                        Intent intentAccount = new Intent(SystemFramework.getInstance()
                                .getGlobalContext(), WebViewActivity.class);
                        intentAccount.putExtra(WebViewActivity.EXTRA_TITLE, "");
                        intentAccount.putExtra(WebViewActivity.EXTRA_URL, weburl);
                        startActivity(intentAccount);
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                break;
            case ("gohome"):
                startActivity(YMXMainActivity.buildExitIntent(SystemFramework.getInstance()
                        .getGlobalContext(), false));
                break;
            case ("order_detail"):
                int orderId = Integer.parseInt(uri.getQueryParameter("order_id"));
                Intent orderIntent = new Intent(SystemFramework.getInstance().getGlobalContext(),
                        OrderDetailActivity.class);
                orderIntent.putExtra(OrderDetailActivity.EXTRA_ORDER_ID, orderId);
                startActivity(orderIntent);
                break;

            default:
                break;
        }

    }

}
